/*
 * Copyright 2005-2013 sxhuayuan.com. All rights reserved.
 * Support: http://www.sxhuayuan.com
 * License: http://www.sxhuayuan.com/license
 */
package com.sxhuayuan.parking.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.sxhuayuan.parking.service.CacheService;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

/**
 * Service - 缓存
 * 
 * @author gaoyan
 * @version 1.0
 */
@Service("cacheServiceImpl")
public class CacheServiceImpl implements CacheService {

	@Autowired
	CacheManager cacheManager;
	@Autowired
	private ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource;

	public String getDiskStorePath() {
		return cacheManager.getConfiguration().getDiskStoreConfiguration().getPath();
	}

	public int getCacheSize() {
		int cacheSize = 0;
		String[] cacheNames = cacheManager.getCacheNames();
		if (cacheNames != null) {
			for (String cacheName : cacheNames) {
				Ehcache cache = cacheManager.getEhcache(cacheName);
				if (cache != null) {
					cacheSize += cache.getSize();
				}
			}
		}
		return cacheSize;
	}

	public int getCacheSize(String cacheName) {
		int cacheSize = 0;
		Ehcache cache = cacheManager.getEhcache(cacheName);
		if (cache != null) {
			cacheSize = cache.getSize();
		}
		return cacheSize;
	}

	@CacheEvict(value = { "setting" }, allEntries = true)
	public void clear() {
		reloadableResourceBundleMessageSource.clearCache();
	}

	public void put(String cacheName, String key, Object value) {
		Assert.notNull(key, "");
		Ehcache cache = cacheManager.getEhcache(cacheName);
		Assert.notNull(cache, "");
		cache.put(new Element(key, value));
	}

	public void delete(String cacheName, String key) {
		Assert.notNull(key, "");
		Ehcache cache = cacheManager.getEhcache(cacheName);
		Assert.notNull(cache, "");
		cache.remove(key);
	}

}